package com.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.common.utils.HttpUtils;
import com.gulimall.member.entity.MemberLevelEntity;
import com.gulimall.member.execption.PhoneExsitException;
import com.gulimall.member.execption.UsernameExsitException;
import com.gulimall.member.service.MemberLevelService;
import com.gulimall.member.vo.MemberLoginVo;
import com.gulimall.member.vo.MemberRegistVo;
import com.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.gulimall.member.dao.MemberDao;
import com.gulimall.member.entity.MemberEntity;
import com.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;


    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        String uid = socialUser.getUid();
        //判断当前用户是否已经注册过
        MemberEntity member = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (member != null){
            //有注册,更新令牌和时间
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setId(member.getId());
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            baseMapper.updateById(memberEntity);
            member.setAccessToken(socialUser.getAccess_token());
            member.setExpiresIn(socialUser.getExpires_in());
            return member;
        }else {
            //待注册
            MemberEntity regist = new MemberEntity();
            HashMap<String, String> map = new HashMap<>();
            map.put("access_token",socialUser.getAccess_token());
            map.put("uid",socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "GET", new HashMap<String, String>(), map);
            try {
                if (response.getStatusLine().getStatusCode() == 200){
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(name);
                    regist.setGender(gender.equals("m")?1:0);

                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } finally {
                MemberLevelEntity memberLevelEntity = memberLevelService.getDefaultLeve();
                regist.setLevelId(memberLevelEntity.getId());
                regist.setSocialUid(socialUser.getUid());
                regist.setAccessToken(socialUser.getAccess_token());
                regist.setExpiresIn(socialUser.getExpires_in());
                baseMapper.insert(regist);
                return regist;
            }
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginactt = vo.getLoginactt();
        String password = vo.getPassword();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginactt).or().eq("mobile", loginactt));
        if (memberEntity == null){
            return null;
        }
        String passworddb = memberEntity.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //密码匹配
        boolean matches = passwordEncoder.matches(password, passworddb);
        if (matches){
            return memberEntity;
        }
        return null;
    }

    @Override
    public void regist(MemberRegistVo memberRegistVo) {
        MemberEntity memberEntity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelService.getDefaultLeve();
        memberEntity.setLevelId(memberLevelEntity.getId());
        //手机号,检查手机号和用户名是否唯一(让controller能感知异常)
        checkPhoneUnique(memberRegistVo.getPhone());
        checkUserNameUnique(memberRegistVo.getUserName());
        memberEntity.setMobile(memberRegistVo.getPhone());
        memberEntity.setUsername(memberRegistVo.getUserName());
        //密码，加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(memberRegistVo.getPassWord());

        //默认昵称
        memberEntity.setNickname(memberRegistVo.getUserName());
        memberEntity.setPassword(encode);


        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String email) throws PhoneExsitException{
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", email));
        if (mobile>0){
            throw new PhoneExsitException();
        }

    }

    @Override
    public void checkUserNameUnique(String userName) throws UsernameExsitException{
        Integer username = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (username>0){
            throw new UsernameExsitException();
        }

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

}